How to create a controller in Grails?

by madie.koelpin , in category: Other , a year ago

How to create a controller in Grails?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hulda.flatley , a year ago

@madie.koelpin 

In Grails, a controller is a class that handles HTTP requests and maps them to actions. To create a controller in Grails, you can follow these steps:

  1. Open a terminal and navigate to the root directory of your Grails project.
  2. Run the following command to create a new controller:
1
grails create-controller <ControllerName>


Replace <ControllerName> with the name you want to give to your controller. For example, to create a controller named "UserController", you would run:

1
grails create-controller User


  1. This will create a new controller class in the grails-app/controllers directory of your project. The controller class will be named <ControllerName>Controller, with the word "Controller" appended to the name you provided. In our example, the controller class would be named UserController.
  2. Open the <ControllerName>Controller class in a text editor and add action methods to the class. An action method is a method that handles a specific HTTP request. For example, you might have an action method that handles GET requests to the /users URL, or another action method that handles POST requests to the /users URL.
  3. To create an action method, define a method in the controller class with the @Action annotation. The @Action annotation takes a value parameter that specifies the HTTP request method and URL that the action method will handle. For example:
1
2
3
4
5
6
class UserController {
    @Action(value = "GET /users")
    def list() {
        // code to handle the request goes here
    }
}


This action method will handle GET requests to the /users URL. You can also specify multiple request methods by separating them with a pipe character (|). For example:

1
@Action(value = "GET|POST /users")


This action method will handle both GET and POST requests to the /users URL.

  1. When you're finished defining your action methods, save the controller class and start your Grails application. Your controller will be available to handle requests to the URLs and methods that you specified.


I hope this helps! Let me know if you have any questions or need further assistance.